package api

import (
	"encoding/hex"
	"net/http"
	"openzbox.com/frame/echo"
	"openzbox.com/gateway/core"
	"openzbox.com/log"
	"openzbox.com/utils"
)

func TestCommand(c echo.Context) error {
	rest := utils.ResponseSuccess("")
	var poll core.Poll
	err := c.Bind(&poll)
	if err != nil {
		rest.Code = 1
		rest.Desc = "参数错误"
		return c.JSON(http.StatusOK, rest)
	}
	bytes, err := core.Mybox.SendPoll(poll)
	if err != nil {
		rest.Code = 1
		rest.Desc = "指令执行出错:" + err.Error()
		log.Error(err)
		return c.JSON(http.StatusOK, rest)
	}
	//log.Info(bytes)
	rest.Data = hex.EncodeToString(bytes[:])
	return c.JSON(http.StatusOK, rest)
}

func NewCommand(c echo.Context) error {
	rest := utils.ResponseSuccess("")
	var poll core.Poll
	err := c.Bind(&poll)
	if err != nil {
		rest.Code = 1
		rest.Desc = "参数错误"
		return c.JSON(http.StatusOK, rest)
	}
	err = core.Mybox.AddCommand(poll)
	if err != nil {
		rest.Code = 1
		rest.Desc = err.Error()
	}
	return c.JSON(http.StatusOK, rest)
}

func ListCommand(c echo.Context) error {
	return c.JSON(http.StatusOK, core.Mybox.Commands)
}

func GetCommand(c echo.Context) error {
	id := c.Param("id")
	poll := core.Mybox.GetCommand(id)
	return c.JSON(http.StatusOK, poll)
}

func UpdateCommand(c echo.Context) error {
	rest := utils.ResponseSuccess("")
	var poll core.Poll
	err := c.Bind(&poll)
	if err != nil {
		rest.Code = 1
		rest.Desc = "参数错误"
		return c.JSON(http.StatusOK, rest)
	}
	err = core.Mybox.UpdateCommand(poll)
	if err != nil {
		rest.Code = 1
		rest.Desc = err.Error()
	}
	return c.JSON(http.StatusOK, rest)
}

func DeleteCommand(c echo.Context) error {
	rest := utils.ResponseSuccess("")
	var polls []core.Poll
	err := c.Bind(&polls)
	if err != nil {
		rest.Code = 1
		rest.Desc = "参数错误"
		return c.JSON(http.StatusOK, rest)
	}
	err = core.Mybox.DeleteCommand(polls)
	if err != nil {
		rest.Code = 1
		rest.Desc = err.Error()
	}
	return c.JSON(http.StatusOK, rest)
}
